<template>
  <div class="table">
    <div class="buttonControl" v-if="isControl">
      <div class="left">
        <template v-if="leftbtn.length > 0">
          <vButton
            v-for="(btn, btnIndex) in leftbtn"
            :key="btnIndex"
            :type="btn.type"
            @click="btn.click"
          >
            {{ btn.title }}
          </vButton>
        </template>
      </div>
      <div class="right">
        <!-- <a-dropdown v-if="isScreen"> -->
        <a-dropdown v-if="isScreen" :open="true">
          <vButton type="default">
            <div>筛选</div>
            <div class="icon"><DownOutlined /></div>
          </vButton>
          <template #overlay>
            <a-menu>
              <a-checkbox
                v-model:checked="checkAll"
                v-model:indeterminate="indeterminate"
                @change="onCheckAllChange"
              >
                全选
              </a-checkbox>

              <a-tree
                :replaceFields="{ key: 'dataIndex' }"
                :autoExpandParent="true"
                v-model:expandedKeys="expandedKeys"
                v-model:selectedKeys="selectedKeys"
                v-model:checkedKeys="checkedKeys"
                checkable
                :tree-data="columnsList"
                @check="treeCheck"
              ></a-tree>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </div>
    <a-table
      :rowKey="rowKey"
      :bordered="bordered"
      :columns="headData"
      :data-source="dataList"
      :pagination="isPagination ? paginationConfig : isPagination"
      @change="tablePaginationChange"
    >
      <template #headerCell="{ title, column }">
        <slot name="tableHeader" :column="column" :title="title"></slot>
      </template>
      <template #bodyCell="{ column, text, record, index }">
        <slot
          name="tableBody"
          :column="column"
          :text="text"
          :record="record"
          :index="index"
        />
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { DownOutlined } from "@ant-design/icons-vue";
import vButton from "../button/Index.vue";
import { ref, toRefs, reactive, onMounted, computed } from "vue";
const props = defineProps({
  leftbtn: Array,
  isControl: {
    type: Boolean,
    default: true,
  },
  isScreen: {
    type: Boolean,
    default: true,
  },
  columnsList: {
    type: Array,
    default: [],
  },
  dataList: Array,
  bordered: {
    type: Boolean,
    default: false,
  },
  rowKey: { type: String, default: "key" },
  isPagination: {
    type: Boolean,
    default: true,
  },
  paginationConfig: {
    type: Object,
    default: () => ({
      showTotal: (total) => `共 ${total} 条`,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ["10", "20", "30", "40"],
      defaultCurrent: 1,
      defaultPageSize: 10,
    }),
  },
});
const {
  leftbtn,
  isControl,
  isScreen,
  bordered,
  columnsList,
  dataList,
  rowKey,
  isPagination,
  paginationConfig,
} = toRefs(props);
const selectedKeys = ref([]);
const checkedKeys = ref([]);
const checkAll = ref(false);
const indeterminate = ref(true);
const onCheckAllChange = (e) => {
  checkAll.value = e.target.checked;
  indeterminate.value = false;

  const findScreen = (list) =>
    list.map((item) => {
      if (item.children) {
        const children = findScreen(item.children);
        item.children = children;
        item.screen = e.target.checked;
      }
      if (item.screen) {
        checkedKeys.value.push(item.dataIndex);
        checkedKeys.value = [...new Set(checkedKeys.value)];
      } else {
        const index = checkedKeys.value.indexOf(item.dataIndex);
        console.log("index", index, item.dataIndex);
        if (index !== -1) {
          checkedKeys.value.splice(index, 1);
        }
      }
      return { ...item, screen: e.target.checked };
    });
  if (!checkAll.value) {
    checkedKeys.value = [];
    selectedKeys.value = [];
  }
  columnsList.value = findScreen(JSON.parse(JSON.stringify(columnsList.value)));
};
const expandedKeys = computed(() => {
  let expanded = [];
  const findChildren = (tableHeaderList) => {
    tableHeaderList.forEach((element) => {
      if (element.children) {
        expanded.push(element?.dataIndex);
        findChildren(element.children);
      }
    });
    return expanded;
  };
  return findChildren(columnsList.value);
});
onMounted(() => {
  const findChecked = (tree) => {
    tree.forEach((item) => {
      if (item.children) {
        findChecked(item.children);
      }
      if (item.screen) {
        checkedKeys.value.push(item.dataIndex);
      }
    });
  };
  findChecked(columnsList.value);
});
const headData = computed(() => {
  if (isScreen.value) {
    const findHeadData = (list) => {
      return list
        .filter((item) => {
          if (item.children) {
            const children = findHeadData(item.children);
            item.children = children;
            item.screen = item.children.some((item) => item.screen);
          }
          if (item.screen) {
            return item;
          }
        })
        .filter(Boolean);
    };
    let dataList = JSON.parse(JSON.stringify(columnsList.value));
    checkAll.value = dataList.every((item) => item.screen);
    indeterminate.value = !dataList.every((item) => item.screen);
    return findHeadData(dataList);
  } else {
    return columnsList.value;
  }
});

const emit = defineEmits(["change"]);
const treeCheck = (checkedKey) => {
  const findScreen = (list) => {
    return list.map((item) => {
      if (item.children) {
        item.children = findScreen(item.children);
      }
      if (checkedKey.length > 0) {
        if (checkedKey.includes(item.dataIndex)) {
          item.screen = true;
        } else {
          item.screen = false;
        }
      } else {
        item.screen = false;
      }

      return item;
    });
  };
  let columnsLists = findScreen(columnsList.value);
  checkAll.value = columnsLists.every((item) => item.screen);
  indeterminate.value = !columnsLists.every((item) => item.screen);
  console.log("columnsLists", checkAll.value, indeterminate.value, columnsLists);
};
const tablePaginationChange = (pagination, filters, sorter, { currentDataSource }) => {
  emit("change", pagination, filters, sorter, { currentDataSource });
};
</script>

<style lang="scss" scoped>
.buttonControl {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
  .right {
    .button-default {
      width: 80px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
.ant-checkbox-wrapper {
  padding-left: 2.4rem;
}
:deep(.ant-table-thead) {
  tr {
    th {
      background-color: #f2f2f2;
      color: rgb(102, 102, 102);
      font-family: "微软雅黑";
      font-size: 14px;
      font-weight: 400;
      letter-spacing: 2px;
    }
  }
}
</style>
